package com.mgface.thymeleaf.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import com.mgface.thymeleaf.util.SwissKnife;

public class ThymeleafStaticResourceFilter extends OncePerRequestFilter{
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		try {
			ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
			templateResolver.setTemplateMode("HTML5");
	        templateResolver.setPrefix("/WEB-INF/error/");
	        templateResolver.setSuffix(".html");
	        templateResolver.setCacheable(true);
	        templateResolver.setCacheTTLMs(3600000L);
	        TemplateEngine templateEngine = new TemplateEngine();
	        templateEngine.setTemplateResolver(templateResolver);
	        WebContext ctx = new WebContext(request, response, getServletContext(), request.getLocale());
	        ctx.setVariable("context", SwissKnife.getBasePath(request, response));
	        templateEngine.process("404", ctx, response.getWriter());
	        response.setContentType("text/html;charset=utf-8");
	        response.setHeader("Pragma", "no-cache");
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expires", 1000);
	    } catch (Exception e) {
	        throw new ServletException(e);
	    }
		
	}


}
